import os
import shutil
import uuid

from zeus.operation_service.app.constant import UPLOAD_DIR
from zeus.operation_service.app.core.asset import ASSET_PATH
from zeus.operation_service.app.core.file_util import FileUtil, U_RW


def zip_asset(asset_dir_path, item_dir, scene_dir):
    tmp_asset_dir = os.path.join(UPLOAD_DIR, str(uuid.uuid1()))
    if os.path.isdir(tmp_asset_dir):
        FileUtil.dir_remove(tmp_asset_dir)
    config_data = [f"item_dir={item_dir}", f"scene_dir={scene_dir}",
                    f"asset_name={os.path.basename(asset_dir_path)}"]
    try:
        shutil.copytree(asset_dir_path, tmp_asset_dir)
        # 拷贝资产包打包脚本
        shutil.copyfile(os.path.join(os.path.dirname(__file__), 'package_asset.sh'), os.path.join(tmp_asset_dir, 'package_asset.sh'))
        config_package_fd = os.open(os.path.join(tmp_asset_dir, 'package_config.conf'), os.O_WRONLY | os.O_CREAT,
                                    U_RW)
        with os.fdopen(config_package_fd, 'w') as f:
            for line in config_data:
                f.write(line + "\n")
        FileUtil.zip_dir(tmp_asset_dir,
                            os.path.join(ASSET_PATH, 'asset_download', f"{os.path.basename(asset_dir_path)}.zip"))
    finally:
        FileUtil.dir_remove(tmp_asset_dir)
